package com.it.cloud.producer.threadWork;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 生产者--多线程
 */
public class MultiThreadProducer {

    public static void main(String[] args) {
        Properties props = new Properties();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        // 生产者
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(props);

        // 线程池
        ExecutorService executor = Executors.newFixedThreadPool(5);
        ProducerRecord<String, String> record;

        try {
            for (int i = 0; i < 10; i++) {
                record = new ProducerRecord<String, String>("my-topic", Integer.toString(i), Integer.toString(i));
                executor.submit(new KafkaProducerThread(producer, record));
            }

            Thread.sleep(3000);
        } catch (Exception e) {
            System.out.println("Send message exception" + e);
        } finally {
            producer.close();
            executor.shutdown();
        }
    }
}
